import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/NewLogin/LoginViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/GYSData.dart';
import 'package:flutter_ahj_app/base/cunchu/Constant.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/downloadfile/sp_util.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

class LogInPage1 extends BaseStatefulWidget {
  String type;

  final String inputVC; // 从那个界面 进来 如果 从 商城 商品详情 进来 登陆之后 返回 原来界面

  LogInPage1({this.inputVC});
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return new LoginPageState(type);
  }
}

class LoginPageState extends BaseState<LoginViewModel, LogInPage1> {
  TextEditingController _nameContro = new TextEditingController(text: '');
  static const communicateChannel = MethodChannel('xinAnLi');
  String type;

  LoginPageState(this.type);

  bool check = true;
  String showMiMa = "1";
  String isLogIng = "0";
  String pwd = "";

  String loginType = "0"; //0：账号密码登录 1：验证码登录

  List<String> _hjName = List();
  List<String> _hjApiPath = List();
  List<String> _hjH5Path = List();
  List<DropdownMenuItem> _hjItems = new List();
  int _curHj = 0;

  @override
  initState() {
    super.initState();
  }

  void isShowMiMa() {
    setState(() {
      showMiMa == "1" ? showMiMa = "0" : showMiMa = "1";
    });
  }

  @override
  Widget initWidget() {
    Row avatar = new Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Image.asset(
          "img/login_logo.png",
          width: Dimens.dimens64,
          height: Dimens.dimens64,
        ),
      ],
    );
    Row avatartext = new Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          "欢迎登录青柠",
          style: new TextStyle(color: SQColor.white, fontSize: 16),
        )
      ],
    );
    Container container = new Container(
      child: new Container(
        color: SQColor.secondary1,
        alignment: Alignment.center,
        height: 48,
        child: CircularProgressIndicator(),
      ),
    );
    RaisedButton sure = new RaisedButton(
      child: new Container(
        alignment: Alignment.center,
        height: 48,
        child: new Text(
          "登录",
          style: new TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      color: SQColor.secondary1,
      disabledColor: SQColor.secondary1,
      textColor: Colors.white,
      onPressed: () {
        FocusScope.of(context).requestFocus(FocusNode());
        loginType == "0" ? _umLogin() : _ucLogin();
      },
    );
    return new Scaffold(
      appBar: MTopBar(
          title: "用户登录",
          elevation: 0,
          rightButtonText: '游客模式',
          onRightButtonClick: () {
            Navigator.pushNamedAndRemoveUntil(
                context, "/home", (check) => false);
          }).create(),
      resizeToAvoidBottomInset: true,
      backgroundColor: SQColor.theme_color,
      body: Container(
        child: Padding(
          padding: EdgeInsets.fromLTRB(Dimens.dimens24, 0, Dimens.dimens24, 0),
          child: new ListView(
            children: <Widget>[
              Offstage(
                offstage: HttpBaseConst.serverUrl == "https://api.xinanyun.cn/",
                child: DropdownButton(
                  isExpanded: true,
                  items: _hjItems,
                  hint: new Text('选择环境'),
                  //当没有默认值的时候可以设置的提示
                  value: _curHj,
                  //下拉菜单选择完之后显示给用户的值
                  onChanged: (t) {
                    //下拉菜单item点击之后的回调
                    setState(() {
                      _curHj = t;
                    });
                    HttpBaseConst.baseH5Url = _hjH5Path[_curHj];
                    HttpBaseConst.serverUrl = _hjApiPath[_curHj];
                    SpUtil.putInt("curHj", _curHj);
                    ToastUtils.showToast(HttpBaseConst.serverUrl);
                  },
                  //设置阴影的高度
                  style: new TextStyle(
                      //设置文本框里面文字的样式
                      color: SQColor.black_333333),
                  iconSize: 24, //设置三角标icon的大小
                ),
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                child: avatar,
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                child: avatartext,
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                child: _loginTypeView(),
              ),
              _loginView(),
              new Container(
                margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                child: GestureDetector(
                  child: Row(
                    children: <Widget>[
//                      new GestureDetector(
//
//                          child:  Text(
//                            "忘记密码",
//                            style: new TextStyle(
//                                color: SQColor.white,
//                                fontSize: Dimens.textSize28,
//                                fontWeight: FontWeight.bold),
//                          ),
//                          onTap: () {
//                            Navigator.pushNamed(context, "/ForgetPWD1").then((value) {
//                              if (value != null && value == "success") {
//                                // 密码修改成功
//                                print("密码修改成功");
//                              }
//                            });
//                          }
//                      ),
//                      Expanded(
//                          child:new Container(),
//                      flex: 1,
//                      ),
                      new GestureDetector(
                          child: Text(
                            "忘记密码",
                            style: new TextStyle(
                                color: SQColor.white,
                                fontSize: Dimens.textSize28,
                                fontWeight: FontWeight.bold),
                          ),
                          onTap: () {
                            Navigator.pushNamed(context, "/ForgetPWD1")
                                .then((value) {
                              if (value != null && value == "success") {
                                // 密码修改成功
                                print("密码修改成功");
                              }
                            });
                          }),
                    ],
                  ),
                ),
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(
                    Dimens.dimens36, Dimens.dimens64, Dimens.dimens36, 0),
                child: isLogIng == "0" ? sure : container,
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(0, Dimens.dimens24, 0, 0),
                child: GestureDetector(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "我无登录账号，去",
                        style: new TextStyle(
                            color: SQColor.white, fontSize: Dimens.textSize28),
                      ),
                      Text(
                        "注册",
                        style: new TextStyle(
                            color: SQColor.white,
                            fontSize: Dimens.textSize28,
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  onTap: () {
                    Navigator.pushNamed(context, "/regist");
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _loginTypeView() {
    return Row(
      children: <Widget>[
        Container(
//          margin: EdgeInsets.fromLTRB(loginType == "0" ? 0 : Dimens.dimens6,
//              Dimens.dimens8, Dimens.dimens6, Dimens.dimens8),
          child: Text(
            "${loginType == "0" ? "账号登录" : "短信验证码登录"}",
            style:
                new TextStyle(color: Colors.white, fontSize: Dimens.textSize32),
          ),
        ),
        Expanded(
          flex: 1,
          child: Container(),
        ),
        GestureDetector(
          child: Container(
            child: Text(
              loginType == "1" ? "账号登录>" : "短信验证码登录>",
              style: new TextStyle(
                  color: Colors.white, fontSize: Dimens.textSize28),
            ),
          ),
          onTap: () {
            setState(() {
              if (loginType == "0")
                loginType = "1";
              else
                loginType = "0";
            });
          },
        ),
      ],
    );
  }

  _loginView() {
    return loginType == "0" ? _umLoginView() : _ucLoginView();
  }

  _umLoginView() {
    TextField name = new TextField(
        autofocus: true,
        decoration: new InputDecoration(
          labelText: "用户名",
          labelStyle: new TextStyle(color: Colors.white54),
          hintStyle: new TextStyle(color: Colors.white70),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white30, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: Colors.white, //边框颜色为绿色
            width: 1, //宽度为5
          )),
        ),
        controller: _nameContro,
        style: new TextStyle(color: SQColor.white),
        cursorColor: SQColor.white,
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    TextField password = new TextField(
      inputFormatters: [
        // WhitelistingTextInputFormatter(RegExp("[0-9]|[a-z]|[A-Z]")),
      ],
      decoration: InputDecoration(
        labelText: "密码",
        labelStyle: new TextStyle(color: Colors.white54),
        hintStyle: new TextStyle(color: Colors.white70),
        suffixIcon: new IconButton(
            icon: Icon(
              showMiMa == "1" ? Icons.visibility_off : Icons.visibility,
              color: Colors.white,
            ),
            onPressed: isShowMiMa),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Colors.white30, //边线颜色为黄色
            width: 1, //边线宽度为2
          ),
        ),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(
          color: Colors.white, //边框颜色为绿色
          width: 1, //宽度为5
        )),
      ),
      obscureText: showMiMa == "1" ? true : false,
      controller: TextEditingController.fromValue(
        TextEditingValue(
            text: pwd,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: pwd.length))),
      ),
      style: new TextStyle(color: SQColor.white),
      cursorColor: SQColor.white,
      onChanged: (String str) {
        setState(() {
          pwd = str;
        });
      },
//      onChanged: ,
    );
    return Column(
      children: <Widget>[
        name,
        password,
      ],
    );
  }

  TextEditingController _phoneController = new TextEditingController(text: ''),
      _checkController = new TextEditingController(text: '');
  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器
  _ucLoginView() {
    TextField _tfPhone = TextField(
        decoration: InputDecoration(
          labelText: "手机号",
          labelStyle: new TextStyle(color: Colors.white54),
          hintStyle: new TextStyle(color: Colors.white70),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white30, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: Colors.white, //边框颜色为绿色
            width: 1, //宽度为5
          )),
        ),
        controller: _phoneController,
        style: TextStyle(color: SQColor.white),
        cursorColor: SQColor.white,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    GestureDetector _rbGetCheck = GestureDetector(
      child: new Container(
        alignment: Alignment.center,
        height: Dimens.dimens36,
        width: Dimens.dimens96,
        child: Text(
          _checkText,
          style: new TextStyle(
              fontSize: Dimens.textSize28,
              color:
                  _checkText == "获取验证码" ? SQColor.white : SQColor.per60Black),
        ),
      ),
      onTap: _checkText == "获取验证码" ? () => _getCheckCode() : null,
    );

    TextField _tfCheck = TextField(
        decoration: InputDecoration(
          labelText: "验证码",
          labelStyle: new TextStyle(color: Colors.white54),
          hintStyle: new TextStyle(color: Colors.white70),
          suffixIcon: _rbGetCheck,
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: Colors.white30, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: Colors.white, //边框颜色为绿色
            width: 1, //宽度为5
          )),
        ),
        controller: _checkController,
        style: TextStyle(color: SQColor.white),
        cursorColor: SQColor.white,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(6),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    return Column(
      children: <Widget>[
        _tfPhone,
        _tfCheck,
      ],
    );
  }

  // 获取验证码
  _getCheckCode() async {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    if (_phoneController.text == null || _phoneController.text.trim() == "") {
      ToastUtils.showToast("请输入手机号");
      return;
    }
    bool matched = exp.hasMatch(_phoneController.text);
    if (!matched) {
      ToastUtils.showToast("请输入正确格式的手机号");
      return;
    }
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      ToastUtils.showToast("请检查手机网络设置");
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });

    viewModel.getCheckCode(_phoneController.text);
    Stream stream = viewModel.getCheckCodeStream();
    stream.listen((baseData) {
      if (baseData != null && baseData.code == 0) {
        ToastUtils.showToast(baseData.msg);
      } else if (baseData != null && baseData.code == 1) {
        ToastUtils.showToast(baseData.msg);
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      } else {
        ToastUtils.showToast("验证码获取失败");
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
    countDownTimer = null;
  }

  _checkLoginResult(Map userBeanEntity) async {
    if (userBeanEntity != null && userBeanEntity['code'] == 0) {
      UserInfoUtils.setUserToken(userBeanEntity['accessToken']);
      print(UserInfoUtils.getUserToken());

      viewModel.changeRoles();
      Stream stream = viewModel.getRoleStream();
      stream.listen((result) {
        if (result == null || result["code"] != 0) {
          UserInfoUtils.setUserToken("");
          ToastUtils.showToast("登录失败");
          isLogIng = "0";
          setState(() {});
        } else {
          saveUserData(userBeanEntity);
        }
      });
    } else if (userBeanEntity != null && userBeanEntity['code'] == 1) {
      ToastUtils.showToast(userBeanEntity['message']);
      isLogIng = "0";
      setState(() {});
    } else {
      final connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ToastUtils.showToast("请检查手机网络设置");
      } else {
        ToastUtils.showToast("账号密码错误");
      }
      isLogIng = "0";
      setState(() {});
    }
  }

  var encryptedString;

  _umLogin() async {
    String password = pwd;
    var encryptedString =
        await communicateChannel.invokeMethod('passwordAes', password);
    isLogIng = "1";
    setState(() {});
    viewModel.setlogInData(_nameContro.text, encryptedString);
    Stream<Map> sss = viewModel.getDataStream();
    sss.listen((userBeanEntity) {
      _checkLoginResult(userBeanEntity);
    });
  }

  _ucLogin() async {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    if (_phoneController.text == null || _phoneController.text.trim() == "") {
      ToastUtils.showToast("请输入手机号");
      return;
    }
    bool matched = exp.hasMatch(_phoneController.text);
    if (!matched) {
      ToastUtils.showToast("请输入正确格式的手机号");
      return;
    }
    if (_checkController.text == null || _checkController.text.trim() == "") {
      ToastUtils.showToast("请输入验证码");
      return;
    }
    isLogIng = "1";
    setState(() {});
    viewModel.checkCodeLogin(_phoneController.text, _checkController.text);
    Stream<Map> stream = viewModel.getCheckCodeLoginStream();
    stream.listen((userBeanEntity) {
      _checkUCLoginResult(userBeanEntity);
    });
  }

  _checkUCLoginResult(Map userBeanEntity) async {
    if (userBeanEntity != null && userBeanEntity['code'] == 0) {
      UserInfoUtils.setUserToken(userBeanEntity['accessToken']);
      print(UserInfoUtils.getUserToken());

      viewModel.changeRoles();
      Stream stream = viewModel.getRoleStream();
      stream.listen((result) {
        if (result == null || result["code"] != 0) {
          UserInfoUtils.setUserToken("");
          ToastUtils.showToast("登录失败");
          isLogIng = "0";
          setState(() {});
        } else {
          saveUserData(userBeanEntity);
        }
      });
    } else if (userBeanEntity != null && userBeanEntity['code'] == 1) {
      ToastUtils.showToast(userBeanEntity['message']);
      isLogIng = "0";
      setState(() {});
    } else {
      final connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ToastUtils.showToast("请检查手机网络设置");
      } else {
        ToastUtils.showToast("账号密码错误");
      }
      isLogIng = "0";
      setState(() {});
    }
  }

  saveUserData(Map userBeanEntity) {
    // isLogIng = "0";
    // UserInfoUtils.setUserNiceName(userBeanEntity.realName);
    // UserInfoUtils.setUserRealName(userBeanEntity.realName);
    // UserInfoUtils.setUserName(_nameContro.text);
    // UserInfoUtils.setPassWord(encryptedString);
    // UserInfoUtils.setUserCompanyName(userBeanEntity.companyName);
    // UserInfoUtils.setUserCompanyID(userBeanEntity.tenantId);
    // UserInfoUtils.setUserAvatarName(userBeanEntity.avatar);
    // UserInfoUtils.setUserToken(userBeanEntity.accessToken);

    // print(UserInfoUtils.getUserToken());
    // UserInfoUtils.setUserId(userBeanEntity.userId.toString());
    // UserInfoUtils.setUserdeptName(userBeanEntity.deptName);
    // UserInfoUtils.setUserdeptCode(userBeanEntity.deptCode);
    // UserInfoUtils.setUserdeptIde(userBeanEntity.deptId);
    // UserInfoUtils.setSID(userBeanEntity.sid);
    // UserInfoUtils.setMID(userBeanEntity.ecId);
    // UserInfoUtils.setPW(userBeanEntity.pw);

    // viewModel.getCheckToken();

    viewModel.gysInfo();

    Stream<GYSInfo> stream = viewModel.gysInfoStream();
    stream.listen((result) async {
      if (result == null) {
        viewModel.getUserRole();
        Stream<int> streamrole = viewModel.getUserRoleStream();

        streamrole.listen((event) {
          if (event == 2) {
            //风险管理师
            UserInfoUtils.setUserType(Constant.USER_RISK_MANAG);
          } else {
            UserInfoUtils.setUserType(Constant.USER_TYPE_DEDAULT);
          }
          if (widget.inputVC == '商品详情') {
            Navigator.pop(context, '刷新');
          } else {
            Navigator.pushNamedAndRemoveUntil(
                context, "/home", (check) => false);
          }
        });
      } else {
        UserInfoUtils.setUserType(Constant.USER_TYPE_GYS);
        UserInfoUtils.setGYSID("${result.supplierId}");
        UserInfoUtils.setGYSName(result.supplierName);
        UserInfoUtils.setGYSPic(result.photoUrl);
        if (widget.inputVC == '商品详情') {
          Navigator.pop(context, '刷新');
        } else {
          Navigator.pushNamedAndRemoveUntil(context, "/home", (check) => false);
        }
      }
    });
  }

  seterrorData(String errorData) {
    ToastUtils.showToast("账号密码错误");
    setState(() {
      isLogIng = "0";
    });
  }
}
